/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import entidades.Newlong;
import entidades.Uteco;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletOutputStream;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.HorizontalAlignment;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;

/**
 *
 * @author SBernardez
 */
public class Pdf extends HttpServlet {

    @Override
	public void init(ServletConfig conf) throws ServletException
		{
		super.init(conf);
		}

    @Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
		{
		try{
//			// Obtengo el tipo.
			String tipo = (request.getParameter("tipo") != null)? request.getParameter("tipo") : "";

                        response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition","attachment;filename=" + tipo + ".pdf");

                        ServletOutputStream outputStream = response.getOutputStream();

			if(tipo.compareTo("cargaTrabajoNewlong") == 0)
				{ generatePdf(request, outputStream); }
                        if(tipo.compareTo("cargaTrabajoUteco") == 0)
				{ generatePdfUteco(request, outputStream); }
			outputStream.flush();
			outputStream.close();
			}catch(Exception e) {}

		response.sendRedirect(request.getParameter("redirect"));
  


}

    public void generatePdf(HttpServletRequest request, OutputStream outputStream) throws SQLException, BadElementException, IOException, DocumentException{
        PdfWriter writer = null;
        Document document = new Document();
        List<Date> fechas = new ArrayList<Date>();
        String[] array = request.getParameter("fechas").substring(1, request.getParameter("fechas").length()-1).split(",");
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd/MM/yyyy");
        for (String s : array){
            try {
                fechas.add(formatoDelTexto.parse(s));
            } catch (ParseException ex) {
                Logger.getLogger(Pdf.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            writer = PdfWriter.getInstance(document, outputStream);
        } catch (DocumentException ex) {
            Logger.getLogger(Pdf.class.getName()).log(Level.SEVERE, null, ex);
        }
        List<Newlong> newlongs = Newlong.listar();
        document.open();
        for (int i = 0; i < newlongs.size(); i++) {
             PdfContentByte contentByte = writer.getDirectContent();
             PdfTemplate template = contentByte.createTemplate(200, 100);
             Graphics2D graphics2d = template.createGraphics(200, 100, new DefaultFontMapper());
             Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 200, 100);
             Newlong newlong = newlongs.get(i);
             JFreeChart chart = generateBarChart(fechas, newlong);
             chart.draw(graphics2d, rectangle2d);
             graphics2d.dispose();

//             contentByte.addTemplate(template, x, y);
             BufferedImage bufferedImage = chart.createBufferedImage(550, 300);
             Image image = Image.getInstance(writer, bufferedImage, 1.0f);

             document.add(image);
           }

       document.close();

    }

      public JFreeChart generateBarChart(List<Date> fechas, Newlong newlong) throws SQLException {
        DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        for (int f = 0; f < fechas.size() - 1; f++) {
            Date fecha1 = fechas.get(f);
            Date fecha2 = fechas.get(f + 1);
            dataSet.setValue(newlong.getCantidadAlDia(fecha1, fecha2), "Adelantado", sdf.format(fecha1));
            dataSet.setValue(newlong.getCantidadDemorado(fecha1, fecha2), "Al Dia", sdf.format(fecha1));
            dataSet.setValue(newlong.getCantidadAdelantados(fecha1, fecha2), "Demorado", sdf.format(fecha1));

        }

        JFreeChart chart = ChartFactory.createBarChart(newlong.getDescripcion(), "Fecha", "Porcentaje",
                dataSet, PlotOrientation.VERTICAL, true, true, true);
       chart.setBackgroundPaint(Color.WHITE);
       CategoryPlot plot =(CategoryPlot) chart.getPlot();
       BarRenderer barRenderer = (BarRenderer)plot.getRenderer();
       barRenderer.setSeriesPaint(0, Color.blue);
       barRenderer.setSeriesPaint(1, Color.MAGENTA);
       barRenderer.setSeriesPaint(2, Color.YELLOW);
       barRenderer.setShadowVisible(false);
       Font font = plot.getDomainAxis().getLabelFont();
       font.deriveFont(8);
       Font f = font.deriveFont(Font.TRUETYPE_FONT, 8);
       plot.getDomainAxis().setTickLabelFont(f);
       plot.getRangeAxis().setTickLabelFont(f);
       plot.setRangeCrosshairVisible(true);
       plot.setRangeCrosshairLockedOnData(true);
       plot.setBackgroundPaint(Color.WHITE);
       plot.getRangeAxis().setRange(0, 150);
       plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
       chart.setPadding(new RectangleInsets(10, 5, 5, 5));
       chart.getLegend().setHorizontalAlignment(HorizontalAlignment.LEFT);
       chart.getLegend().setPosition(RectangleEdge.RIGHT);
       chart.getLegend().setBorder(0.0, 0.0, 0.0, 0.0);
       chart.getLegend().setBackgroundPaint(new Color(255,255,255,0));

       return chart;
    }

    public void generatePdfUteco(HttpServletRequest request, OutputStream outputStream) throws SQLException, BadElementException, DocumentException, IOException{
        PdfWriter writer = null;
        Document document = new Document();
        List<Date> fechas = new ArrayList<Date>();
        String[] array = request.getParameter("fechas").substring(1, request.getParameter("fechas").length()-1).split(",");
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd/MM/yyyy");
        for (String s : array){
            try {
                fechas.add(formatoDelTexto.parse(s));
            } catch (ParseException ex) {
                Logger.getLogger(Pdf.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            writer = PdfWriter.getInstance(document, outputStream);
        } catch (DocumentException ex) {
            Logger.getLogger(Pdf.class.getName()).log(Level.SEVERE, null, ex);
        }
        List<Uteco> utecos = Uteco.listar();
        document.open();
        for (int i = 0; i < utecos.size(); i++) {
             PdfContentByte contentByte = writer.getDirectContent();
             PdfTemplate template = contentByte.createTemplate(200, 100);
             Graphics2D graphics2d = template.createGraphics(200, 100, new DefaultFontMapper());
             Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, 200, 100);
             Uteco uteco = utecos.get(i);
             JFreeChart chart = generateBarChartUteco(fechas, uteco);
             chart.draw(graphics2d, rectangle2d);
             graphics2d.dispose();
             BufferedImage bufferedImage = chart.createBufferedImage(550, 300);
             Image image = Image.getInstance(writer, bufferedImage, 1.0f);

             document.add(image);
           }

       document.close();
    }

     public JFreeChart generateBarChartUteco(List<Date> fechas, Uteco uteco) throws SQLException {
        DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        for (int f = 0; f < fechas.size() - 1; f++) {
            Date fecha1 = fechas.get(f);
            Date fecha2 = fechas.get(f + 1);
            dataSet.setValue(uteco.getCantidadAdelantados(fecha1, fecha2), "Adelantado", sdf.format(fecha1));
            dataSet.setValue(uteco.getCantidadAlDia(fecha1, fecha2), "Al Dia", sdf.format(fecha1));
            dataSet.setValue(uteco.getCantidadDemorado(fecha1, fecha2), "Demorado", sdf.format(fecha1));
        }

        JFreeChart chart = ChartFactory.createBarChart(uteco.getDescripcion(), "Fecha", "Porcentaje",
                dataSet, PlotOrientation.VERTICAL, true, true, true);


       chart.setBackgroundPaint(Color.WHITE);
       CategoryPlot plot =(CategoryPlot) chart.getPlot();
       BarRenderer barRenderer = (BarRenderer)plot.getRenderer();
       barRenderer.setSeriesPaint(0, Color.blue);
       barRenderer.setSeriesPaint(1, Color.MAGENTA);
       barRenderer.setSeriesPaint(2, Color.YELLOW);
       Font font = plot.getDomainAxis().getLabelFont();
       font.deriveFont(8);
       Font f = font.deriveFont(Font.TRUETYPE_FONT, 8);
       plot.getDomainAxis().setTickLabelFont(f);
       plot.getRangeAxis().setTickLabelFont(f);

//       plot.setRangeCrosshairVisible(true);
       plot.setRangeCrosshairLockedOnData(true);
       plot.setBackgroundPaint(Color.WHITE);
       plot.getRangeAxis().setRange(0, 100);
       
       plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
       chart.setPadding(new RectangleInsets(10, 5, 5, 5));
       chart.getLegend().setHorizontalAlignment(HorizontalAlignment.LEFT);
       chart.getLegend().setPosition(RectangleEdge.RIGHT);
       chart.getLegend().setBorder(0.0, 0.0, 0.0, 0.0);
       chart.getLegend().setBackgroundPaint(new Color(255,255,255,0));

       return chart;
    }



}


